<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getRoleListApi, updateRoleInfo } from '@/api/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElTag } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { RoleListItem } from '@/api/role/type'

import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getRoleListApi()
    return {
      list: res.data || [],
      total: res.data.length
    }
  }
})

const { dataList, loading, total } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'name',
    label: t('role.roleName'),
    formatter: (data: RoleListItem) => {
      return data.name == 'admin' ? '管理员' : '委办局'
    },
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'role',
    label: '角色类型',
    formatter: (data: RoleListItem) => {
      return data.role == 'admin' ? '管理员' : '普通用户'
    },
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'applyTime',
    label: '创建时间',
    slots: {
      default: () => {
        return (
          <span>{new Date('2024-07-04').toLocaleString('zh-CN', { timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' })}</span>
        )
      }
    },
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'enabled',
    label: t('menu.status'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag type={data.row.enabled ? 'success' : 'danger'}>
              {data.row.enabled ? t('userDemo.enable') : t('userDemo.disable')}
            </ElTag>
          </>
        )
      }
    },
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="danger">{t('exampleDemo.del')}</BaseButton>
          </>
        )
      }
    },
    align: 'center',
    headerAlign: 'center',
    minWidth: 240,
    fixed: 'right'
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'roleName',
    label: t('role.roleName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  // dialogTitle.value = t('exampleDemo.add')
  // currentRow.value = undefined
  // dialogVisible.value = true
  // actionType.value = ''
  ElMessage.warning('该功能暂未开放')
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData?.routes.length) {
    saveLoading.value = true
    updateRoleInfo(formData.name, formData.routes.join(','), formData.enabled).then((res) => {
      if (res.data === 'success') {
        if (userStore.getUserInfo?.role === formData.name) {
          ElMessage.success('当前用户绑定的角色信息更新成功，即将重新登录以更新权限')
          setTimeout(() => {
            userStore.logout()
          }, 1000);
        } else {
          ElMessage.success('角色信息更新成功')
        }
      } else {
        ElMessage.error('角色信息更新失败，请重试')
      }
      getList()
      saveLoading.value = false
      dialogVisible.value = false
    })
  } else {
    ElMessage.error('请选择开启的功能权限，至少保留首页权限')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table :columns="tableColumns" default-expand-all node-key="name" :data="dataList" :loading="loading" :pagination="{
      total
    }" @register="tableRegister" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-else :current-row="currentRow" />

    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
